package com.mdnote.structure.linked_list;

import java.util.Objects;

/**
 * @author Rhythm-2019
 * @date 2020/8/11
 * @description
 */
public class DoubleLinkedList<T> {

    private static class Node<T> {
        private T val;
        private Node<T> pre;
        private Node<T> next;

        public Node(T val) {
            this.val = val;
        }
    }

    private Node<T> head;

    public DoubleLinkedList() {
        this.head = new Node<T>(null);
    }

    // 添加到嘴鸥
    public void add(Node<T> node) {
        Node<T> cur = this.head;
        while (cur.next != null) {
            cur = cur.next;
        }
        cur.next = node;
        node.pre = cur;
    }
    // 指定位置后面添加
    public void add(Node<T> pre, Node<T> node) {
        Node<T> cur = this.head;
        while (cur != null) {
            if (cur == pre) {
                break;
            }
            cur = cur.next;
        }
        if (cur == null) {
            System.out.println("找不到对应的数据");
        } else {
            if (cur.next == null) {
                cur.next = node;
                node.pre = cur;
            } else {
                cur.next.pre = node;
                node.next = cur.next;
                cur.next = node;
                node.pre = cur;
            }
        }
    }

    // 删除
    public void remove(Node<T> node) {
        Node<T> cur = this.head;
        while (cur != null) {
            if (cur == node) {
                break;
            }
            cur = cur.next;
        }
        // 找不到
        if (cur == null) {
            System.out.println("找不到该元素");
        } else {
            cur.pre.next = cur.next;
            if (cur.next != null) {
                cur.next.pre = cur.pre;
            }
        }


    }
    // 修改

    // 展示
    public void show() {
        Node<T> cur = this.head.next;
        while (cur != null) {
            System.out.println(cur.val);
            cur = cur.next;
        }
    }

    public static void main(String[] args) {
        DoubleLinkedList<Integer> list = new DoubleLinkedList<>();
        Node<Integer> node1 = new Node<>(11);
        Node<Integer> node2 = new Node<>(22);
        Node<Integer> node3 = new Node<>(33);
        list.add(node1);
        list.add(node2);
        list.add(node3);

//        list.show();
        list.add(node3, new Node<Integer>(15));
        list.remove(node3);
        list.show();
    }
}
